<template>
  <div class="clipping-page-container">
    <!-- 顶部工具栏 -->
    <div class="top-toolbar">
      <div class="toolbar-left">
        <el-button @click="goBack" size="small" class="action-btn">
          <el-icon>
            <ArrowLeft />
          </el-icon>
          返回列表
        </el-button>
        <el-button type="primary" @click="submitClip" :loading="submitting" size="small" class="action-btn start-btn">
          <el-icon>
            <Scissor />
          </el-icon>
          开始拆条
        </el-button>
      </div>
      <div class="toolbar-center">
        <span class="page-title">视频拆条</span>
      </div>
      <div class="toolbar-right">
        <el-button @click="showClient" size="small" class="action-btn">
          <el-icon>
            <Help />
          </el-icon>
          客户端拆条工具
        </el-button>
      </div>
    </div>

    <!-- 主要内容区域 -->
    <div class="editor-container">
      <!-- 左侧信息面板 -->
      <div class="info-panel">
        <!-- 视频信息卡片 -->
        <div class="video-info-card">
          <h3 class="card-title">视频信息</h3>
          <div class="info-content">
            <div class="info-item">
              <label>视频名称</label>
              <span>{{ recording.name || '未加载' }}</span>
            </div>
            <div class="info-item">
              <label>时长</label>
              <span>{{ formatTime(duration) }}</span>
            </div>
            <div class="info-item">
              <label>格式</label>
              <span>{{ recording.format || 'MP4' }}</span>
            </div>
            <div class="info-item">
              <label>大小</label>
              <span>{{ formatFileSize(recording.size) }}</span>
            </div>
            <div class="info-item">
              <label>创建时间</label>
              <span>{{ recording.create_time || '未知' }}</span>
            </div>
          </div>
        </div>  

        <!-- 片段列表 -->
        <div class="records-card">
          <div class="card-header">
            <h3 class="card-title">片段列表</h3>
            <div class="list-info">
              <el-tag type="info" size="small" v-if="clippingRecords.length > 0">
                共 {{ clippingRecords.length }} 个片段
              </el-tag>
            </div>
          </div>
          <div class="records-container">
            <el-scrollbar>
              <div v-if="clippingRecords.length === 0" class="empty-records">
                <el-icon style="margin-right: 8px;">
                  <Plus />
                </el-icon>
                <span>通过时间轴选择片段后，点击"添加到片段列表"按钮</span>
              </div>
              <el-table v-else :data="clippingRecords" size="small" class="records-table">
                  <el-table-column label="名称" width="110">
                    <template #default="scope">
                      <div class="name-cell" :title="scope.row.name">
                        {{ scope.row.name }}
                      </div>
                    </template>
                  </el-table-column>
                  <el-table-column label="时间范围" width="110">
                    <template #default="scope">
                      <div class="time-range">
                        <div class="start-time-line">开始: {{ scope.row.startTime || '00:00:00' }}</div>
                        <div class="end-time-line">结束: {{ scope.row.endTime || '00:00:00' }}</div>
                      </div>
                    </template>
                  </el-table-column>               
                <el-table-column label="操作" width="40" fixed="right" align="center">
                  <template #default="scope">
                    <div class="action-buttons">
                      <el-tooltip content="预览片段" placement="top">
                        <el-button 
                          size="small" 
                          @click="previewClip(scope.row)"
                          class="action-btn"
                          plain
                          :icon="View"
                        />
                      </el-tooltip>
                      <el-tooltip content="删除片段" placement="top">
                        <el-button 
                          size="small" 
                          type="danger"
                          @click="deleteClip(scope.row)"
                          class="action-btn"
                          plain
                          :icon="Delete"
                        />
                      </el-tooltip>
                    </div>
                  </template>
                </el-table-column>
              </el-table>
            </el-scrollbar>
          </div>
        </div>
      </div>

      <!-- 右侧内容区域 -->
      <div class="right-content">
        <!-- 上部内容区域（包含播放器和预览面板） -->
        <div class="upper-section">
          <!-- 中央视频播放区域 -->
          <section class="editor-main">
            <!-- 视频播放器区域 -->
            <div class="player-section">
              <!-- 播放器容器 -->
              <div class="player-container">
                <VideoPlayer ref="mainPlayer" :src="recording?.recording_url" :autoplay="false" :controls="false"
                  @ready="onPlayerReady" @timeupdate="onTimeUpdate" @error="onPlayerError" @play="onPlay" @pause="onPause"
                  class="main-video-player" />
              </div>
            </div>
          </section>

          <!-- 右侧预览面板 -->
          <div class="preview-panel">
            <div class="preview-card">
              <h3 class="card-title">片段预览</h3>
              
              <!-- 预览播放器 -->
              <div class="preview-section">
                <div class="preview-player-wrapper">
                  <VideoPlayer ref="previewPlayer" :src="recording?.recording_url" :autoplay="false" :controls="true"
                    @timeupdate="onPreviewTimeUpdate" @error="onPlayerError"
                    class="preview-video-player" />
                </div>
                
                <!-- 入点出点时间信息 - 紧凑布局 -->
                <div class="time-info-row">
                  <div class="time-item">
                    <label>入点:</label>
                    <span>{{ formatTime(inPointTime) }}</span>
                  </div>
                  <div class="time-separator">→</div>
                  <div class="time-item">
                    <label>出点:</label>
                    <span>{{ formatTime(outPointTime) }}</span>
                  </div>
                  <div class="time-item duration-item">
                    <label>时长:</label>
                    <span>{{ formatTime(clipDuration) }}</span>
                  </div>
                </div>
              </div>
              
              <!-- 拆条配置 -->
              <div class="clip-configuration">
                <div class="clip-name-input">
                  <div class="info-row">
                    <label>拆条名称:</label>
                    <el-input v-model="clippname" placeholder="不填写则使用默认名称" clearable size="small" />
                  </div>
                  
                  <div class="info-row">
                    <label>视频格式:</label>
                    <el-select v-model="clippingForm.format" placeholder="选择视频格式" size="small">
                      <el-option label="mp4" value="mp4" />
                      <el-option label="ts" value="ts" />
                    </el-select>
                  </div>
                  
                  <div class="info-row">
                    <label>转码模板:</label>
                    <el-select v-model="clippingForm.transcodeTemplate" placeholder="选择转码模板" size="small">
                      <el-option label="1080p" value="hd1080" />
                      <el-option label="720p" value="hd720" />
                    </el-select>
                  </div>
                </div>
              
              <!-- 添加到片段列表按钮 -->
              <div class="clip-actions">
                <el-button type="primary" size="small" @click="addClipToRecords">
                  <el-icon>
                    <Plus />
                  </el-icon>添加到片段列表
                </el-button>
              </div>
              </div>
             </div>  
          </div>
        </div>

        <!-- 时间轴区域 -->
        <div class="timeline-section">
          <div class="timeline-header">
            <div class="timeline-controls">
              <el-button size="small" @click="zoomIn" title="放大时间轴">
                <el-icon>
                  <ZoomIn />
                </el-icon>
              </el-button>
              <el-button size="small" @click="zoomOut" title="缩小时间轴">
                <el-icon>
                  <ZoomOut />
                </el-icon>
              </el-button>
              <el-button size="small" @click="fitToScreen" title="适配屏幕">
                <el-icon>
                  <FullScreen />
                </el-icon>
              </el-button>
            </div>

            <!-- 自定义控制器 -->
            <div class="custom-controls">
              <div class="control-group">
                <el-button size="small" @click="stepBackward" title="上一帧">
                  <el-icon>
                    <ArrowLeft />
                  </el-icon><el-icon>
                    <ArrowLeft />
                  </el-icon>
                  上一帧
                </el-button>
                <el-button size="small" @click="rewind" title="快退">
                  <el-icon>
                    <ArrowLeft />
                  </el-icon>
                  快退
                </el-button>
                <el-button size="small" @click="togglePlay" :icon="isPlaying ? VideoPause : VideoPlay" title="播放/暂停">
                  {{ isPlaying ? '暂停' : '播放' }}
                </el-button>
                <el-button size="small" @click="forward" title="快进">
                  <el-icon>
                    <ArrowRight />
                  </el-icon>
                  快进
                </el-button>
                <el-button size="small" @click="stepForward" title="下一帧">
                  <el-icon>
                    <ArrowRight />
                  </el-icon><el-icon>
                    <ArrowRight />
                  </el-icon>
                  下一帧
                </el-button>
              </div>

              <div class="control-group">
                <el-button size="small" @click="setInPoint" :type="hasInPoint ? 'primary' : 'default'" title="设置入点">
                  <el-icon>
                    <Scissor />
                  </el-icon>入点
                </el-button>
                <el-button size="small" @click="setOutPoint" :type="hasOutPoint ? 'primary' : 'default'" title="设置出点">
                  <el-icon>
                    <Scissor />
                  </el-icon>出点
                </el-button>
                <el-button size="small" @click="clearSelection" title="清除选择">
                  <el-icon>
                    <Delete />
                  </el-icon>清除
                </el-button>
              </div>
            </div>

            <div class="timeline-info">
              <span class="selection-info">
                播放时间  {{ formatTime(currentTime) }} / {{ formatTime(duration) }}
              </span>            
            </div>
          </div>

          <!-- 时间轴容器 -->
          <div class="timeline-container" ref="timelineContainer" style="overflow-x: auto; height: 60px !important; flex: none !important;">
            <!-- 时间刻度 -->
            <div class="time-scale" ref="timeScale">
              <div class="scale-marks">             
                <div v-for="mark in timeMarks" :key="mark.time + '-' + mark.major" :style="{ left: mark.position + 'px' }" 
                    :class="['time-mark', { 'major-mark': mark.major }]">
                  <div class="mark-line"></div>
                  <div v-if="mark.major" class="mark-label">{{ mark.label }}</div>
                </div>
              </div>
            </div>
            
            <!-- 播放头 -->
            <div class="playhead" :style="{ left: playheadPosition + 'px' }"
                 @mousedown="startPlayheadDragging($event)"
                 @touchstart="startPlayheadDragging($event)">
              <div class="playhead-line"></div>
              <div class="playhead-knob"></div>
            </div>
            
            <!-- 入点出点标记 -->
            <div v-if="hasInPoint" class="point-marker in-point-marker" :style="{ left: inPointPosition + 'px' }"
                 @mousedown="startTimelineDragging('inPoint', $event)"
                 @touchstart="startTimelineDragging('inPoint', $event)">
              <div class="marker-line"></div>
              <div class="marker-label">入点</div>
            </div>
            <div v-if="hasOutPoint" class="point-marker out-point-marker" :style="{ left: outPointPosition + 'px' }"
                 @mousedown="startTimelineDragging('outPoint', $event)"
                 @touchstart="startTimelineDragging('outPoint', $event)">
              <div class="marker-line"></div>
              <div class="marker-label">出点</div>
            </div>
          </div>

          <!-- 时间轴自定义滑块 -->
          <div class="timeline-scrollbar" ref="timelineScrollbar">
            <div class="scrollbar-track">
              <div 
                class="scrollbar-thumb"
                ref="scrollbarThumb"
                @mousedown="startDragging"
                @touchstart="startDragging"
                :style="{ left: thumbPosition + 'px' }"
              >
                <div class="thumb-indicator left"></div>
                <div class="thumb-indicator right"></div>
              </div>
            </div>
          </div>
        </div>
        <!--入点出点 图片区域 -->
        <div class="image-container">
          <!-- 入点截图区域 -->
          <div class="screenshot-section">
            <!-- <h4>入点截图</h4> -->
            <div class="screenshot-list">
              <div v-if="isLoadingInPointScreenshot" class="screenshot-item">
                <div class="screenshot-placeholder">
                  <el-icon class="loading-spinner"><Loading /></el-icon>
                  <span>加载中...</span>
                </div>
              </div>
              <div v-for="(screenshot, index) in inPointScreenshots" :key="screenshot.timestamp" class="screenshot-item">
                <div class="screenshot-with-overlay">
                  <img 
                    :src="screenshot.data" 
                    :alt="`入点截图 ${formatTime(screenshot.time)}`" 
                    class="screenshot-image"
                    @error="handleScreenshotError('inPoint', index)"
                  />
                  <div class="screenshot-overlay">
                    <div class="overlay-content">
                      <div class="screenshot-type">入点</div>
                      <div class="screenshot-time">{{ formatTime(screenshot.time) }}</div>
                    </div>
                    <button class="delete-btn" @click.stop="clearInPointScreenshot(index)">
                      <el-icon><Close /></el-icon>
                    </button>
                  </div>
                </div>
              </div>
              <div v-if="inPointScreenshots.length === 0 && !isLoadingInPointScreenshot" class="screenshot-item">
                <div class="screenshot-placeholder">
                  <span>未设置入点</span>
                </div>
              </div>
            </div>
            <div v-if="inPointScreenshots.length > 0" class="clear-all-container">
              <button class="clear-all-btn" @click.stop="clearInPointScreenshot()">
                清除所有入点截图
              </button>
            </div>
          </div>
          
          <!-- 出点截图区域 -->
          <div class="screenshot-section">
            <!-- <h4>出点截图</h4> -->
            <div class="screenshot-list">
              <div v-if="isLoadingOutPointScreenshot" class="screenshot-item">
                <div class="screenshot-placeholder">
                  <el-icon class="loading-spinner"><Loading /></el-icon>
                  <span>加载中...</span>
                </div>
              </div>
              <div v-for="(screenshot, index) in outPointScreenshots" :key="screenshot.timestamp" class="screenshot-item">
                <div class="screenshot-with-overlay">
                  <img 
                    :src="screenshot.data" 
                    :alt="`出点截图 ${formatTime(screenshot.time)}`" 
                    class="screenshot-image"
                    @error="handleScreenshotError('outPoint', index)"
                  />
                  <div class="screenshot-overlay">
                    <div class="overlay-content">
                      <div class="screenshot-type">出点</div>
                      <div class="screenshot-time">{{ formatTime(screenshot.time) }}</div>
                    </div>
                    <button class="delete-btn" @click.stop="clearOutPointScreenshot(index)">
                      <el-icon><Close /></el-icon>
                    </button>
                  </div>
                </div>
              </div>
              <div v-if="outPointScreenshots.length === 0 && !isLoadingOutPointScreenshot" class="screenshot-item">
                <div class="screenshot-placeholder">
                  <span>未设置出点</span>
                </div>
              </div>
            </div>
            <div v-if="outPointScreenshots.length > 0" class="clear-all-container">
              <button class="clear-all-btn" @click.stop="clearOutPointScreenshot()">
                清除所有出点截图
              </button>
            </div>
          </div>
        </div>
     </div>
    </div>
  </div>
  
  <!-- 拆条预览对话框 -->
  <clip-preview-dialog v-model:show-preview="showPreview" :current-clip="currentClip" />
       
</template>

<script setup>
import { ref, reactive, computed, onMounted, onUnmounted, watch, nextTick } from 'vue';
import { ElMessage, ElMessageBox } from 'element-plus';
import {
  ArrowLeft, ArrowRight, Scissor, VideoPlay, VideoPause,
  Edit, Delete, View, Help, ZoomIn, ZoomOut, FullScreen,
  Plus, Picture, Loading, Close
} from '@element-plus/icons-vue';
import VideoPlayer from '@/components/VideoPlayer.vue';
import ClipPreviewDialog from './ClipPreviewDialog.vue';
import api from '@/api';
import { useRouter, useRoute } from 'vue-router';

// 路由
const router = useRouter();
const route = useRoute();
const recordingId = route.query.id;

// 预览相关状态 - 简单的本地状态管理
const showPreview = ref(false);
const currentClip = ref(null);

// 状态变量
const mainPlayer = ref(null);
const previewPlayer = ref(null);
const timeScale = ref(null);



const timelineScrollbar = ref(null);
const scrollbarThumb = ref(null);
const recording = ref({});
const duration = ref(1);//刻度时长 单位s
const currentTime = ref(0);
const isPlaying = ref(false);
const submitting = ref(false);
const thumbPosition = ref(0); // 滑块位置
const isDragging = ref(false); // 是否正在拖动滑块
const clipStartTime = ref(''); // 切片开始时间
const clipEndTime = ref(''); // 切片结束时间

// 入点出点截图相关状态
const inPointScreenshots = ref([]);
const outPointScreenshots = ref([]);
const isLoadingInPointScreenshot = ref(false);
const isLoadingOutPointScreenshot = ref(false);

// 时间轴相关
const timelineZoom = ref(2); // 初始缩放比例设为10，适合大多数视频长度
const timelineWidth = computed(() => {
  const width = duration.value * timelineZoom.value;
  console.log('时间轴宽度计算:', duration.value, '秒 *', timelineZoom.value, 'px/秒 =', width, 'px');
  return width;
}); // 时间轴总宽度
const playheadPosition = computed(() => currentTime.value * timelineZoom.value);

// 入点出点选择
const selectionStart = ref(0);
const selectionEnd = ref(0);
const hasInPoint = ref(false);
const hasOutPoint = ref(false);
const inPointPosition = computed(() => selectionStart.value * timelineZoom.value);
const outPointPosition = computed(() => selectionEnd.value * timelineZoom.value);
const selectionStartPosition = computed(() => Math.min(inPointPosition.value, outPointPosition.value));
const selectionEndPosition = computed(() => Math.max(inPointPosition.value, outPointPosition.value));


// 时间刻度生成逻辑 - 简化版本
const timeMarks = computed(() => {
  if (!duration.value || duration.value <= 0) {
    console.log('duration无效，返回空timeMarks数组');
    return [];
  }
  
  const marks = [];
  
  // 固定间隔：10秒一个大竖线（主刻度），1秒一个小竖线（次刻度）
  const MAJOR_INTERVAL = 10; // 10秒一个大竖线
  const MINOR_INTERVAL = 1;  // 1秒一个小竖线
  
  console.log('开始生成timeMarks，duration:', duration.value, '秒，timelineZoom:', timelineZoom.value);
  
  // 主要刻度（大竖线，每10秒）
  for (let time = 0; time <= duration.value; time += MAJOR_INTERVAL) {
    marks.push({
      time: time,
      position: time * timelineZoom.value,
      major: true,
      label: formatTime(time)
    });
  }
  
  // 次要刻度（小竖线，每秒）
  // 仅在缩放比例足够大时显示，避免过于密集
  if (timelineZoom.value >= 1) {
    for (let time = MINOR_INTERVAL; time <= duration.value; time += MINOR_INTERVAL) {
      if (time % MAJOR_INTERVAL !== 0) {
        marks.push({
          time: time,
          position: time * timelineZoom.value,
          major: false
        });
      }
    }
  }
  
  // 强制添加最后一个刻度，确保覆盖完整时长
  if (marks.length > 0 && marks[marks.length - 1].time < duration.value) {
    marks.push({
      time: duration.value,
      position: duration.value * timelineZoom.value,
      major: true,
      label: formatTime(duration.value)
    });
  }
  
  // 按时间排序
  marks.sort((a, b) => a.time - b.time);
  
  console.log('timeMarks生成完成，总数:', marks.length, 
              '个刻度，第一个刻度:', marks[0] ? `时间=${marks[0].time}秒, 位置=${marks[0].position}px` : '空',
              '最后一个刻度:', marks[marks.length-1] ? `时间=${marks[marks.length-1].time}秒, 位置=${marks[marks.length-1].position}px` : '空');
  
  return marks;
});

// 定义timelineContainer引用
const timelineContainer = ref(null);


// 修改播放器就绪函数，优化初始化顺序
const onPlayerReady = async () => {
  try {
    if (mainPlayer.value) {
      console.log('=== 开始获取视频实际时长 ===');
      console.log('当前设置的duration值:', duration.value, '秒');
      
      // 获取视频实际时长
      const actualDuration = await mainPlayer.value.getDuration();
      console.log('从播放器获取的实际时长:', actualDuration, '秒 (约', Math.round(actualDuration / 60), '分钟)');
      
      // 实际使用获取到的视频时长，如果为0则使用默认值
      if (actualDuration > 0) {
        duration.value = actualDuration;
        console.log('已设置为播放器实际时长:', actualDuration, '秒 (约', Math.round(actualDuration / 60), '分钟)');
      } else {
        // 当获取失败时使用默认的正确时长5308.332秒（约1小时28分28秒）
        const defaultDuration = 5308.332;
        duration.value = defaultDuration;
        console.log('获取实际时长失败，使用默认时长:', defaultDuration, '秒 (约', Math.round(defaultDuration / 60), '分钟)');
      }
      
      // 立即适配屏幕
      nextTick(() => {
        fitToScreen();
      });
      
      // 设置默认入点出点位置
      if (duration.value > 0) {
        // 按照用户要求设置：入点初始值为00:00:00，出点初始值为00:00:20
        selectionStart.value = 5; // 入点设为0秒
        selectionEnd.value = Math.min(20, duration.value); // 出点设为20秒，如果视频时长不足20秒则设为视频总时长
        hasInPoint.value = true;
        hasOutPoint.value = true;
        currentTime.value = 0; // 当前时间设为入点位置
        updateClipTimeInputs();
        
        // 获取默认入点出点截图
        setTimeout(() => {
          captureScreenshot(selectionStart.value, 'inPoint');
          captureScreenshot(selectionEnd.value, 'outPoint');
        }, 1000);
      }
    }
  } catch (error) {
    console.error('获取视频时长失败:', error);
    // 如果获取失败，强制设置为正确的时长
    // duration.value = 5308.332;
    console.log('获取失败，已强制设置为正确时长:', duration.value, '秒');
    
    // 立即适配屏幕
    fitToScreen();
  }
};

// 处理截图加载错误
const handleScreenshotError = (pointType, index) => {
  console.error(`${pointType}截图加载失败`);
  if (pointType === 'inPoint' && index !== undefined) {
    // 移除特定索引的截图
    inPointScreenshots.value.splice(index, 1);
  } else if (pointType === 'outPoint' && index !== undefined) {
    // 移除特定索引的截图
    outPointScreenshots.value.splice(index, 1);
  }
};

// 清除入点截图
const clearInPointScreenshot = (index) => {
  if (index !== undefined) {
    // 清除指定索引的截图
    inPointScreenshots.value.splice(index, 1);
  } else {
    // 清除所有入点截图
    inPointScreenshots.value = [];
  }
};

// 清除出点截图
const clearOutPointScreenshot = (index) => {
  if (index !== undefined) {
    // 清除指定索引的截图
    outPointScreenshots.value.splice(index, 1);
  } else {
    // 清除所有出点截图
    outPointScreenshots.value = [];
  }
};

// 获取指定时间点的截图
const captureScreenshot = async (time, pointType) => {
  if (!mainPlayer.value || !time) return null;
  
  // 设置加载状态
  if (pointType === 'inPoint') {
    isLoadingInPointScreenshot.value = true;
  } else if (pointType === 'outPoint') {
    isLoadingOutPointScreenshot.value = true;
  }
  
  try {
    console.log(`开始获取${pointType}时间点${time}的截图`);
    const screenshotData = await mainPlayer.value.getScreenshot(time);
    console.log(`${pointType}截图获取${screenshotData ? '成功' : '失败'}`);
    
    // 保存截图数据到数组
    if (screenshotData) {
      const screenshotInfo = {
        data: screenshotData,
        time: time,
        timestamp: Date.now()
      };
      
      if (pointType === 'inPoint') {
        inPointScreenshots.value.push(screenshotInfo);
      } else if (pointType === 'outPoint') {
        outPointScreenshots.value.push(screenshotInfo);
      }
    }
    
    return screenshotData;
  } catch (error) {
    console.error(`获取${pointType}截图失败:`, error);
    ElMessage.error(`获取${pointType === 'inPoint' ? '入点' : '出点'}截图失败`);
    return null;
  } finally {
    // 重置加载状态
    if (pointType === 'inPoint') {
      isLoadingInPointScreenshot.value = false;
    } else if (pointType === 'outPoint') {
      isLoadingOutPointScreenshot.value = false;
    }
  }
};


// 拆条表单
const clippingForm = reactive({
  format: 'mp4',
  transcodeTemplate: 'hd1080'
});

// 拆条名称
const clippname = ref('');

// 拆条记录
const clippingRecords = ref([]);

// 预览缩略图
const previewThumbnail = ref('');



const clipDuration = computed(() => {
  if (!hasInPoint.value || !hasOutPoint.value) return 0;
  return Math.abs(selectionEnd.value - selectionStart.value);
});

// 入点出点时间计算属性
const inPointTime = computed(() => {
  return hasInPoint.value ? Math.min(selectionStart.value, selectionEnd.value) : 0;
});

const outPointTime = computed(() => {
  return hasOutPoint.value ? Math.max(selectionStart.value, selectionEnd.value) : 0;
});

// 更新时间输入框
const updateClipTimeInputs = () => {
  if (hasInPoint.value && hasOutPoint.value) {
    clipStartTime.value = formatTime(inPointTime.value);
    clipEndTime.value = formatTime(outPointTime.value);
  }
};



// 拖拽状态
const draggingState = ref(null);

// 初始化
onMounted(() => {
  loadRecordingInfo();
  loadClippingRecords();
  
  // 添加窗口大小变化监听
  window.addEventListener('resize', handleResize);
});

// 在组件卸载时清理事件监听
onUnmounted(() => {
  window.removeEventListener('resize', handleResize);
  if (timelineContainer.value) {
    timelineContainer.value.removeEventListener('scroll', updateThumbPosition);
  }
});

// 自定义滑块拖动开始
const startDragging = (event) => {
  event.preventDefault();
  isDragging.value = true;
  
  // 添加鼠标和触摸事件监听
  document.addEventListener('mousemove', handleThumbDrag);
  document.addEventListener('mouseup', stopDragging);
  document.addEventListener('touchmove', handleThumbDrag);
  document.addEventListener('touchend', stopDragging);
};

// 自定义滑块拖动处理
const handleThumbDrag = (event) => {
  if (!isDragging.value || !timelineScrollbar.value || !scrollbarThumb.value || !timelineContainer.value) return;
  
  event.preventDefault();
  
  const trackRect = timelineScrollbar.value.getBoundingClientRect();
  const thumbWidth = scrollbarThumb.value.offsetWidth;
  const containerWidth = trackRect.width - thumbWidth;
  
  // 获取鼠标或触摸位置
  let clientX;
  if (event.type.includes('mouse')) {
    clientX = event.clientX;
  } else if (event.touches && event.touches.length > 0) {
    clientX = event.touches[0].clientX;
  }
  
  // 计算滑块新位置
  let newPosition = clientX - trackRect.left - thumbWidth / 2;
  newPosition = Math.max(0, Math.min(newPosition, containerWidth));
  
  // 更新滑块位置
  thumbPosition.value = newPosition;
  
  // 计算对应的时间轴滚动位置
  const scrollRatio = newPosition / containerWidth;
  const maxScroll = Math.max(0, timelineWidth.value - timelineContainer.value.offsetWidth);
  const newScrollLeft = scrollRatio * maxScroll;
  
  // 同步滚动到时间轴容器
  if (Math.abs(timelineContainer.value.scrollLeft - newScrollLeft) > 2) {
    timelineContainer.value.scrollLeft = newScrollLeft;
  }
};

// 停止拖动
const stopDragging = () => {
  isDragging.value = false;
  document.removeEventListener('mousemove', handleThumbDrag);
  document.removeEventListener('mouseup', stopDragging);
  document.removeEventListener('touchmove', handleThumbDrag);
  document.removeEventListener('touchend', stopDragging);
};

// 点击轨道跳转到对应位置
const handleTrackClick = (event) => {
  if (isDragging.value || event.target === scrollbarThumb.value || !timelineContainer.value) return;
  
  const trackRect = timelineScrollbar.value.getBoundingClientRect();
  const thumbWidth = scrollbarThumb.value.offsetWidth;
  const containerWidth = trackRect.width - thumbWidth;
  
  let clientX;
  if (event.type.includes('mouse')) {
    clientX = event.clientX;
  } else if (event.touches && event.touches.length > 0) {
    clientX = event.touches[0].clientX;
  }
  
  let newPosition = clientX - trackRect.left - thumbWidth / 2;
  newPosition = Math.max(0, Math.min(newPosition, containerWidth));
  
  thumbPosition.value = newPosition;
  
  const scrollRatio = newPosition / containerWidth;
  const maxScroll = Math.max(0, timelineWidth.value - timelineContainer.value.offsetWidth);
  const newScrollLeft = scrollRatio * maxScroll;
  
  if (Math.abs(timelineContainer.value.scrollLeft - newScrollLeft) > 2) {
    timelineContainer.value.scrollLeft = newScrollLeft;
  }
};

// 更新滑块位置以匹配时间轴滚动
const updateThumbPosition = () => {
  if (!timelineScrollbar.value || !scrollbarThumb.value || isDragging.value || !timelineContainer.value) return;
  
  const trackWidth = timelineScrollbar.value.offsetWidth - scrollbarThumb.value.offsetWidth;
  const maxScroll = Math.max(0, timelineWidth.value - timelineContainer.value.offsetWidth);
  
  if (maxScroll === 0) {
    // 如果内容不超出容器，滑块居中显示
    thumbPosition.value = (trackWidth - scrollbarThumb.value.offsetWidth) / 2;
    return;
  }
  
  const scrollRatio = timelineContainer.value.scrollLeft / maxScroll;
  const newPosition = scrollRatio * trackWidth;
  
  if (Math.abs(thumbPosition.value - newPosition) > 1) {
    thumbPosition.value = newPosition;
  }
};

// 添加轨道点击事件监听
nextTick(() => {
  if (timelineScrollbar.value) {
    timelineScrollbar.value.addEventListener('click', handleTrackClick);
    timelineScrollbar.value.addEventListener('touchstart', handleTrackClick);
  }
  
  // 初始化滑块位置
  updateThumbPosition();
  
  // 监听时间轴容器滚动事件，同步更新滑块位置
  if (timelineContainer.value) {
    timelineContainer.value.addEventListener('scroll', updateThumbPosition);
  }
});

// 修改加载录制信息的函数，确保使用播放器获取的实际时长
const loadRecordingInfo = async () => {
  try {
    // 使用测试数据进行开发调试，但不设置固定时长
    const testData = {
      name: '音乐台直播录制20251002',    
      recording_url: 'http://10.168.60.122:8187/view/record/9/index.m3u8'
    };
        
    recording.value = testData;
    // 初始化为0，让onPlayerReady来设置实际时长
    duration.value = 0;
    console.log('=== 加载录制信息 ===');
    console.log('初始duration设置为0，等待播放器获取实际时长');
    
    // 加载拆条记录
    await loadClippingRecords();
  } catch (error) {
    console.error('加载录制信息失败:', error);
    ElMessage.error('加载录制信息失败');
  }
};

// 加载拆条记录
const loadClippingRecords = async () => {
  // try {
  //   const res = await api.get(`/recordings/${recordingId}/clippings`);
  //   clippingRecords.value = res.data.map(record => ({
  //     ...record,
  //     startTime: formatTime(parseFloat(record.start_time || '0')),
  //     endTime: formatTime(parseFloat(record.end_time || '0')),
  //     duration: formatTime(Math.abs(parseFloat(record.end_time || '0') - parseFloat(record.start_time || '0')))
  //   }));
  // } catch (error) {
  //   ElMessage.error('加载拆条记录失败');
  //   console.error('Failed to load clipping records:', error);
  // }
};



// 播放时间更新
const onTimeUpdate = (time) => {
  currentTime.value = time;
  
  // 同步更新自定义滑块位置
  updateThumbPosition();
};

// 播放状态变化
const onPlay = () => {
  isPlaying.value = true;
};

const onPause = () => {
  isPlaying.value = false;
};

// 预览播放器时间更新
const onPreviewTimeUpdate = (time) => {
  // 可以根据需要添加预览播放器的时间更新逻辑
  // 例如，当预览播放器时间到达出点时自动停止
  if (hasOutPoint.value && time >= outPointTime.value) {
    if (previewPlayer.value) {
      previewPlayer.value.pause();
    }
  }
};

// 预览播放器播放状态变化




// 播放错误
const onPlayerError = (error) => {
  ElMessage.error('播放器错误');
  console.error('Player error:', error);
};

// 播放/暂停切换 - 修改为使用组件提供的togglePlay方法
const togglePlay = () => {
  try {
    if (mainPlayer.value) {
      mainPlayer.value.togglePlay();
    } else {
      ElMessage.warning('播放器未就绪');
    }
  } catch (error) {
    console.error('播放/暂停操作失败:', error);
    ElMessage.error('播放/暂停失败，请稍后重试');
  }
};

// 快退 - 修改为使用seek方法
const rewind = () => {
  try {
    if (mainPlayer.value) {
      mainPlayer.value.seek(Math.max(0, currentTime.value - 10));
    }
  } catch (error) {
    console.error('快退操作失败:', error);
    ElMessage.error('快退失败，请稍后重试');
  }
};

// 快进 - 修改为使用seek方法
const forward = () => {
  try {
    if (mainPlayer.value) {
      mainPlayer.value.seek(Math.min(duration.value, currentTime.value + 10));
    }
  } catch (error) {
    console.error('快进操作失败:', error);
    ElMessage.error('快进失败，请稍后重试');
  }
};

// 上一帧 - 修改为使用seek方法
const stepBackward = () => {
  try {
    if (mainPlayer.value) {
      mainPlayer.value.seek(Math.max(0, currentTime.value - 1 / framerate.value));
    }
  } catch (error) {
    console.error('上一帧操作失败:', error);
    ElMessage.error('上一帧失败，请稍后重试');
  }
};

// 下一帧 - 修改为使用seek方法
const stepForward = () => {
  try {
    if (mainPlayer.value) {
      mainPlayer.value.seek(Math.min(duration.value, currentTime.value + 1 / framerate.value));
    }
  } catch (error) {
    console.error('下一帧操作失败:', error);
    ElMessage.error('下一帧失败，请稍后重试');
  }
};

// 设置入点
const setInPoint = async () => {
  selectionStart.value = currentTime.value;
  hasInPoint.value = true;
  updateClipTimeInputs();
  ElMessage.success('入点已设置');
  
  // 获取入点截图
  if (mainPlayer.value) {
    await captureScreenshot(currentTime.value, 'inPoint');
  }
};

// 设置出点
const setOutPoint = async () => {
  selectionEnd.value = currentTime.value;
  hasOutPoint.value = true;
  updateClipTimeInputs();
  ElMessage.success('出点已设置');
  
  // 获取出点截图
  if (mainPlayer.value) {
    await captureScreenshot(currentTime.value, 'outPoint');
  }
};

// 清除选择
const clearSelection = () => {
  hasInPoint.value = false;
  hasOutPoint.value = false;
  clipStartTime.value = '';
  clipEndTime.value = '';
  // 不清除截图列表，只清除选择状态
  ElMessage.info('已清除选择');
};

// 提交拆条任务（批量）
const submitClip = async () => {
  if (clippingRecords.value.length === 0) {
    ElMessage.warning('请先添加片段到列表');
    return;
  }

  submitting.value = true;
  try {
    // 构建批量拆条参数，不包含开始时间和结束时间
    const params = {
      recording_id: recordingId,
      name: clippname.value || `拆条任务_${new Date().toLocaleString()}`,
      // 使用clippname.value作为任务名称，与输入框保持一致
      format: clippingForm.format,
      transcode_template: clippingForm.transcodeTemplate,
      // 片段参数单独放在clips数组中
      clips: clippingRecords.value.map(clip => ({
        start_time: clip.start_time,
        end_time: clip.end_time,
        name: clip.name
      }))
    };

    await api.post('/clippings/batch', params);
    ElMessage.success(`已成功提交${clippingRecords.value.length}个片段的拆条任务`);
    clippingRecords.value = []; // 清空片段列表
    loadClippingRecords(); // 重新加载拆条记录
  } catch (error) {
    ElMessage.error('提交拆条任务失败');
    console.error('Failed to submit batch clipping task:', error);
  } finally {
    submitting.value = false;
  }
};

// 删除拆条记录
const deleteClip = (record) => {
  ElMessageBox.confirm(
    '确定要删除这条拆条记录吗？',
    '删除确认',
    {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    }
  ).then(() => {
    // 查找并删除对应的记录
    const index = clippingRecords.value.findIndex(item => item.id === record.id);
    if (index > -1) {
      clippingRecords.value.splice(index, 1);
      ElMessage.success('删除成功');
    } else {
      ElMessage.error('删除失败：未找到该记录');
    }
  }).catch(() => {
    ElMessage.info('已取消删除');
  });
};

// 预览拆条 - 包含视频URL的实现
const previewClip = (record) => {
  console.log('开始预览拆条:', record);
  console.log('当前recording状态:', recording.value);
  // 创建包含record数据和URL的完整对象
  currentClip.value = {
    ...record, // 包含record的所有属性
    url: recording?.recording_url || 'http://10.168.60.122:8187/view/record/9/index.m3u8' // 确保有URL值
  };
  showPreview.value = true;
};

// 确保recording变量被正确初始化
watch(recording, (newRecording) => {
  console.log('recording变量已更新:', newRecording);
});

// 时间轴缩放 - 按照10倍进行
const zoomIn = () => {
  timelineZoom.value = Math.min(timelineZoom.value * 5, 100); // 最大缩放倍数
};

const zoomOut = () => {
  timelineZoom.value = Math.max(timelineZoom.value / 5, 0.5); // 最小缩放倍数
};

// 简化的fitToScreen函数，适应新的缩放方案
const fitToScreen = () => {
  if (timeScale.value && duration.value > 0) {
    // 找到容器的实际宽度
    const timelineContainerEl = document.querySelector('.timeline-container');
    const actualWidth = timelineContainerEl ? timelineContainerEl.clientWidth : 500;
    const containerWidth = Math.max(actualWidth, 500); // 设置最小宽度
    
    // 计算合适的缩放比例
    let newZoom = containerWidth / duration.value;
    
    // 限制缩放范围
    const minZoom = 0.5;
    const maxZoom = 100;
    
    // 对计算出的缩放值进行10的幂次调整，使其符合10倍缩放的设计理念
    const zoomLog = Math.log10(newZoom);
    const roundedZoomLog = Math.round(zoomLog * 2) / 2; // 四舍五入到最近的0.5倍
    const adjustedZoom = Math.pow(10, roundedZoomLog);
    
    // 应用计算并调整后的缩放比例
    timelineZoom.value = Math.max(Math.min(adjustedZoom, maxZoom), minZoom);
    
    console.log('适配屏幕 - 容器宽度:', containerWidth, 'px, 视频时长:', duration.value, '秒, 实际应用缩放:', timelineZoom.value.toFixed(2), 'px/秒');
    
    // 重置滚动位置到开始
    nextTick(() => {
      if (timelineContainer.value) {
        timelineContainer.value.scrollLeft = 0;
      }
      if (timelineScrollbar.value && timelineScrollbar.value.wrap) {
        timelineScrollbar.value.wrap.scrollLeft = 0;
      }
    });
  }
};

// 监听窗口大小变化，自动适配屏幕
const handleResize = () => {
  fitToScreen();
};

// 监听duration变化，当视频时长确定后自动适配屏幕
watch(duration, (newDuration, oldDuration) => {
  if (newDuration > 0 && newDuration !== oldDuration) {
    nextTick(() => {
      fitToScreen();
    });
  }
});



// 添加片段到列表
const addClipToRecords = () => {
  if (!hasInPoint.value || !hasOutPoint.value) {
    ElMessage.warning('请先选择片段范围');
    return;
  }

  const start = Math.min(selectionStart.value, selectionEnd.value);
  const end = Math.max(selectionStart.value, selectionEnd.value);
  const clipDurationVal = end - start;

  // 创建新的片段记录
  const newClip = {
    id: `clip_${Date.now()}`,
    name: clippname.value || `片段_${formatTime(start)}_${formatTime(end)}`,
    startTime: formatTime(start),
    endTime: formatTime(end),
    duration: formatTime(clipDurationVal),
    status: 'success',
    start_time: start.toString(),
    end_time: end.toString(),
    format: clippingForm.format, // 使用视频格式选择
    transcodeTemplate: clippingForm.transcodeTemplate // 使用转码模板选择
  };

  // 添加到列表
  clippingRecords.value.unshift(newClip);
  ElMessage.success('片段已添加到列表');
};

// 开始播放头拖拽
const startPlayheadDragging = (event) => {
  event.preventDefault();
  draggingState.value = 'playhead';

  const handleMouseMove = (mouseEvent) => {
    if (!draggingState.value || !timeScale.value) return;

    const rect = timeScale.value.getBoundingClientRect();
    const x = mouseEvent.clientX - rect.left;
    const time = Math.max(0, Math.min(duration.value, x / timelineZoom.value));

    // 更新当前时间并让播放器跳转到对应位置
    currentTime.value = time;
    if (mainPlayer.value) {
      mainPlayer.value.seek(time);
    }
    
    // 同步更新滑块位置
    updateThumbPosition();
  };

  const handleMouseUp = () => {
    draggingState.value = null;
    document.removeEventListener('mousemove', handleMouseMove);
    document.removeEventListener('mouseup', handleMouseUp);
  };

  document.addEventListener('mousemove', handleMouseMove);
  document.addEventListener('mouseup', handleMouseUp);
};

// 开始时间轴拖拽（入点出点）
const startTimelineDragging = (type, event) => {
  event.preventDefault();
  draggingState.value = type;

  const handleMouseMove = (mouseEvent) => {
    if (!draggingState.value || !timeScale.value) return;

    const rect = timeScale.value.getBoundingClientRect();
    const x = mouseEvent.clientX - rect.left;
    const time = Math.max(0, Math.min(duration.value, x / timelineZoom.value));

    if (draggingState.value === 'inPoint') {
      selectionStart.value = time;
    } else if (draggingState.value === 'outPoint') {
      selectionEnd.value = time;
    }

    updateClipTimeInputs();
  };

  const handleMouseUp = () => {
    draggingState.value = null;
    document.removeEventListener('mousemove', handleMouseMove);
    document.removeEventListener('mouseup', handleMouseUp);
  };

  document.addEventListener('mousemove', handleMouseMove);
  document.addEventListener('mouseup', handleMouseUp);
};

// 显示客户端拆条工具信息
const showClient = () => {
  ElMessageBox.alert(
    `
    <div style="padding: 20px;">
      <h3 style="margin-top: 0; color: #333;">客户端拆条工具</h3>
      <p style="margin-bottom: 15px;">网页版工具提供基础的视频拆条功能，如果您需要进行更复杂的剪辑操作，推荐使用我们的PC客户端。</p>
      
      <div style="margin-bottom: 15px;">
        <h4 style="margin-top: 0; margin-bottom: 10px; color: #555;">客户端优势：</h4>
        <ul style="margin: 0; padding-left: 20px;">
          <li style="margin-bottom: 5px;">添加和编辑字幕</li>
          <li style="margin-bottom: 5px;">添加视频特效和转场效果</li>
          <li style="margin-bottom: 5px;">添加背景音乐和音效</li>
          <li style="margin-bottom: 5px;">高级视频滤镜和调色功能</li>
          <li style="margin-bottom: 5px;">多轨道编辑能力</li>
          <li style="margin-bottom: 5px;">更稳定的视频处理性能</li>
        </ul>
      </div>
      
      <div style="margin-bottom: 20px;">
        <h4 style="margin-top: 0; margin-bottom: 10px; color: #555;">客户端下载地址：</h4>
        <p style="color: #1890ff;">https://example.com/download/client</p>
      </div>
      
      <div style="text-align: center;">
        <a href="https://example.com/download/client" target="_blank" style="
          display: inline-block;
          padding: 10px 20px;
          background-color: #1890ff;
          color: white;
          text-decoration: none;
          border-radius: 4px;
          transition: background-color 0.3s;
        " onmouseover="this.style.backgroundColor='#40a9ff'" onmouseout="this.style.backgroundColor='#1890ff'">
          下载PC客户端
        </a>
      </div>
    </div>
    `,
    '客户端拆条工具',
    {
      dangerouslyUseHTMLString: true,
      showConfirmButton: false,
      cancelButtonText: '',
      center: true
    }
  );
};

// 返回列表
const goBack = () => {
  router.push('/recording-clipping');
};

// 工具函数：格式化时间
const formatTime = (seconds) => {
  // 确保seconds是有效数字
  const numSeconds = typeof seconds === 'number' && !isNaN(seconds) ? seconds : 0;
  const hrs = Math.floor(numSeconds / 3600);
  const mins = Math.floor((numSeconds % 3600) / 60);
  const secs = Math.floor(numSeconds % 60);
  return `${hrs.toString().padStart(2, '0')}:${mins.toString().padStart(2, '0')}:${secs.toString().padStart(2, '0')}`;
};

// 工具函数：解析时间
const parseTime = (timeString) => {
  const parts = timeString.split(':').map(Number);
  if (parts.length === 3) {
    return parts[0] * 3600 + parts[1] * 60 + parts[2];
  } else if (parts.length === 2) {
    return parts[0] * 60 + parts[1];
  }
  return parseFloat(timeString) || 0;
};

// 工具函数：格式化文件大小
const formatFileSize = (bytes) => {
  if (!bytes) return '0 B';
  const k = 1024;
  const sizes = ['B', 'KB', 'MB', 'GB', 'TB'];
  const i = Math.floor(Math.log(bytes) / Math.log(k));
  return parseFloat((bytes / Math.pow(k, i)).toFixed(2)) + ' ' + sizes[i];
};
</script>

<style scoped lang="scss">
// 全局样式重置和基础设置
.clipping-page-container {
  display: flex;
  flex-direction: column;
  height: 100%;
  width: 100%;
  background-color: #f5f5f5;
  overflow: hidden;
  position: relative;
}

/* 全局滚动条样式重置 */
* {
  scrollbar-width: thin;
  scrollbar-color: #c0c4cc #f0f2f5;
}

*::-webkit-scrollbar {
  width: 6px;
  height: 6px;
}

*::-webkit-scrollbar-track {
  background-color: #f0f2f5;
}

*::-webkit-scrollbar-thumb {
  background-color: #c0c4cc;
  border-radius: 3px;
}

// 顶部工具栏
.top-toolbar {
  display: flex;
  align-items: center;
  justify-content: space-between;
  padding: 12px 20px;
  background-color: #fff;
  border-bottom: 1px solid #e0e0e0;
  box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);

  .toolbar-left,
  .toolbar-right {
    display: flex;
    align-items: center;
    gap: 10px;
  }

  .toolbar-center {
    display: flex;
    align-items: center;

    .page-title {
      font-size: 18px;
      font-weight: 600;
      color: #333;
    }
  }

  .action-btn {
    border-radius: 4px;
    transition: all 0.3s ease;
    
    
    &:hover {
      transform: translateY(-1px);
      box-shadow: 0 2px 8px rgba(0, 0, 0, 0.15);
    }
  }

  .start-btn {
    background-color: #1890ff;
    border-color: #1890ff;

    &:hover {
      background-color: #40a9ff;
      border-color: #40a9ff;
    }
  }
}

// 主编辑器容器
.editor-container {
  display: flex;
  flex-direction: row;
  flex: 1;
  overflow: hidden;
  background-color: #fafafa;
}

// 左侧信息面板
.info-panel {
  width: 300px;
  background-color: #fff;
  border-right: 1px solid #e0e0e0;
  display: flex;
  flex-direction: column;
  overflow: hidden;
}

// 右侧内容区域
.right-content {
  flex: 1;
  display: flex;
  flex-direction: column;
  overflow: hidden;
}

// 上部内容区域（包含播放器和预览面板）
.upper-section {
  height: 55vh; /* 与播放器高度保持一致 */
  display: flex;
  overflow: hidden;
  min-height: 0;
}

// 中央播放器区域
.editor-main {
  flex: 1;
  display: flex;
  flex-direction: column;
  overflow: hidden;
  background-color: #f0f2f5;
}

// 右侧预览面板
.preview-panel {
  width: 300px;
  background-color: #fff;
  border-left: 1px solid #e0e0e0;
  display: flex;
  flex-direction: column;
  overflow: hidden;
}

// 预览播放器区域样式
.preview-section {
  margin-bottom: 8px;
}

.preview-player-wrapper {
  width: 100%;
  height: 160px;
  position: relative;
  background-color: #000;
  border-radius: 6px;
  margin-bottom: 8px;
  display: flex;
  align-items: center;
  justify-content: center;
  overflow: visible !important;
  min-height: unset !important;
}

.preview-video-player {
  width: 100%;
  height: 100%;
  object-fit: cover;
}

.preview-player-wrapper .video-js {
  width: 100% !important;
  height: 100% !important;
  position: relative !important;
  min-height: unset !important; /* 移除最小高度限制 */
}

.preview-player-wrapper .vjs-tech {
  object-fit: cover !important; /* 确保视频内容填充整个容器 */
  width: 100% !important;
  height: 100% !important;
}

/* 确保所有容器元素都没有最小高度限制 */
.preview-player-wrapper .video-player-container {
  min-height: unset !important;
  height: 100% !important;
}

.preview-player-wrapper .video-wrapper {
  min-height: unset !important;
  height: 100% !important;
}

.preview-player-wrapper .video-wrapper :deep(.video-js) {
  min-height: unset !important;
  height: 100% !important;
}

/* 恢复大播放按钮的默认行为 - 仅在暂停和未开始播放时显示 */
.preview-player-wrapper .vjs-big-play-button {
  display: block !important;
  position: absolute !important;
  top: 50% !important;
  left: 50% !important;
  transform: translate(-50%, -50%) !important;
  opacity: 1 !important;
  transition: opacity 0.3s !important;
}

/* 播放时隐藏大播放按钮 */
.preview-player-wrapper .vjs-playing .vjs-big-play-button {
  opacity: 0 !important;
}

/* 恢复控件栏的默认悬浮行为 */
.preview-player-wrapper .vjs-control-bar {
  opacity: 1 !important; /* 初始可见 */
  visibility: visible !important;
  position: absolute !important;
  bottom: 0 !important;
  left: 0 !important;
  right: 0 !important;
  height: 3.5em !important;
  background: linear-gradient(to top, rgba(0,0,0,0.7) 0%, rgba(0,0,0,0) 100%) !important;
  transition: opacity 0.3s !important;
}

/* 鼠标悬停时控件栏保持可见 */
.preview-player-wrapper:hover .vjs-control-bar {
  opacity: 1 !important;
}

/* 进度条样式优化 */
.preview-player-wrapper .vjs-progress-control {
  display: flex !important;
  flex: 1 !important;
  order: 1 !important;
}

.preview-player-wrapper .vjs-progress-holder {
  height: 100% !important;
  min-height: 10px !important;
  margin: 0 10px !important;
}

.preview-player-wrapper .vjs-play-progress,
.preview-player-wrapper .vjs-load-progress,
.preview-player-wrapper .vjs-load-progress div {
  height: 100% !important;
}

/* 确保所有控制按钮正常显示 */
.preview-player-wrapper .vjs-play-control,
.preview-player-wrapper .vjs-volume-control,
.preview-player-wrapper .vjs-fullscreen-control,
.preview-player-wrapper .vjs-time-control {
  display: flex !important;
  visibility: visible !important;
  opacity: 1 !important;
}

/* 确保时间显示正常 */
.preview-player-wrapper .vjs-current-time-display,
.preview-player-wrapper .vjs-time-divider,
.preview-player-wrapper .vjs-duration-display {
  display: block !important;
  padding: 0 5px !important;
}

// 时间信息行 - 紧凑布局
.time-info-row {
  display: flex;
  align-items: center;
  justify-content: space-between;
  padding: 8px 12px;
  background-color: #fff;
  border-radius: 6px;
  border: 1px solid #e8e8e8;
  box-shadow: 0 1px 2px rgba(0, 0, 0, 0.05);
  font-size: 13px;
}

.time-item {
  display: flex;
  flex-direction: column;
  align-items: center;
  text-align: center;
  flex: 1;
}

.time-item label {
  color: #666;
  font-size: 12px;
  margin-bottom: 2px;
}

.time-item span {
  color: #333;
  font-weight: 500;
  font-size: 13px;
  min-width: 80px;
  overflow: hidden;
  text-overflow: ellipsis;
  white-space: nowrap;
}

.time-separator {
  color: #ccc;
  font-size: 14px;
  margin: 0 4px;
}

.duration-item {
  flex: 1.2;
}



.info-row label {
  color: #666;
  font-weight: 500;
  min-width: 60px;
}

.info-row span {
  color: #333;
  font-weight: 500;
  font-family: 'Monaco', 'Menlo', 'Ubuntu Mono', monospace;
}

// 拆条配置容器样式
.clip-configuration {
  margin-bottom: 16px;
}

// 拆条配置区域样式
.clip-configuration {
  margin-bottom: 12px;
}

// 拆条名称输入区域样式
.clip-name-input {
  margin-bottom: 0;
  padding: 12px;
  background-color: #fff;
  border-radius: 6px;
  border: 1px solid #e8e8e8;
  box-shadow: 0 1px 3px rgba(0, 0, 0, 0.05);
}

// 信息行样式 - 紧凑布局
.clip-name-input .info-row {
  display: flex;
  align-items: center;
  margin-bottom: 6px;
  font-size: 13px;
  padding: 2px 0;
}

.clip-name-input .info-row:last-child {
  margin-bottom: 0;
}

.clip-name-input .info-row label {
  width: 70px;
  margin-right: 8px;
  color: #333;
  font-size: 13px;
  flex-shrink: 0;
}

// 表单元素样式 - 紧凑布局
.clip-name-input .el-input,
.clip-name-input .el-select {
  flex: 1;
  max-width: 200px;
}

.clip-name-input .el-input__wrapper,
.clip-name-input .el-select .el-input__wrapper {
  height: 32px !important;
}

.clip-name-input .el-input__inner,
.clip-name-input .el-select .el-input__inner {
  height: 32px !important;
  line-height: 32px !important;
  font-size: 13px;
}

// 响应式设计，在小屏幕上适应宽度
@media screen and (max-width: 768px) {
  .preview-player-wrapper {
    height: 120px; /* 小屏幕上进一步减小播放器高度 */
  }
  
  .clip-name-input .el-input,
  .clip-name-input .el-select {
    width: 100% !important;
    max-width: none !important;
  }
  
  .time-info-row {
    flex-direction: column;
    gap: 8px;
  }
  
  .time-item {
    width: 100%;
  }
  
  .time-separator {
    display: none;
  }
  
  .clip-name-input .info-row {
    flex-direction: column;
    align-items: flex-start;
    gap: 4px;
  }
  
  .clip-name-input .info-row label {
    width: auto;
    margin-right: 0;
  }
}

// 按钮区域样式
.clip-actions {
  margin-top: 8px;
  text-align: center;
}

.clip-actions .el-button {
  width: 100%;
  font-size: 14px;
  transition: all 0.3s ease;
}

.clip-actions .el-button:hover {
  transform: translateY(-1px);
  box-shadow: 0 4px 12px rgba(45, 140, 240, 0.25);
}

// 表单元素样式优化
.info-row .el-input, .info-row .el-select {
  transition: all 0.3s ease;
}

.info-row .el-input:hover, .info-row .el-select:hover {
  border-color: #409eff;
}

.info-row .el-input__inner:focus, .info-row .el-select .el-input__inner:focus {
  border-color: #409eff;
  box-shadow: 0 0 0 2px rgba(64, 158, 255, 0.2);
}

// 卡片通用样式
.video-info-card,
.params-card {
  padding: 16px;
  border-bottom: 1px solid #e8e8e8;
  background-color: #fff;

  .card-title {
    font-size: 10px;
    font-weight: 600;
    color: #333;
    margin-bottom: 8px;
    padding-bottom: 8px;
    border-bottom: 1px solid #f0f0f0;
  }
}

// 片段列表面板 - 添加固定高度和滚动支持
.records-card {
  padding: 16px;
  border-bottom: 1px solid #e8e8e8;
  background-color: #fff;
  //max-height: 400px; // 设置最大高度，内容多时会出现滚动条
  overflow: hidden;
  display: flex; // 设置为弹性容器
  flex-direction: column; // 垂直方向布局

  .card-title {
    font-size: 14px;
    font-weight: 600;
    color: #333;
    margin-bottom: 12px;
    padding-bottom: 8px;
    border-bottom: 1px solid #f0f0f0;
  }
}

// 预览面板中的卡片样式
.preview-card {
  padding: 16px;
  background-color: #fff;
  flex-shrink: 0;
  overflow: hidden;
  height: 100%;
  display: flex;
  flex-direction: column;

  .card-title {
    font-size: 16px;
    font-weight: 600;
    color: #333;
    margin-bottom: 5px;
    padding-bottom: 8px;
    border-bottom: 1px solid #f0f0f0;
  }
}

// 参数卡片样式
.params-card {
  padding: 16px;
  border-bottom: 1px solid #e8e8e8;
  background-color: #fff;
  flex-shrink: 0;
  overflow: hidden;

  .card-title {
    font-size: 14px;
    font-weight: 600;
    color: #333;
    margin-bottom: 12px;
    padding-bottom: 8px;
    border-bottom: 1px solid #f0f0f0;
  }
}

// 视频信息
.info-content {
  .info-item {
    display: flex;
    justify-content: space-between;
    align-items: center;
    margin-bottom: 8px;
    font-size: 12px;

    label {
      color: #666;
      font-weight: 500;
    }

    span {
      color: #333;
      max-width: 150px;
      text-align: right;
      white-space: nowrap;
      overflow: hidden;
      text-overflow: ellipsis;
    }
  }
}

// 表单样式
.el-form {
  .el-form-item {
    margin-bottom: 12px;

    .el-form-item__label {
      font-size: 12px;
      color: #666;
      padding: 0 0 4px 0;
    }
  }
}

// 记录列表
.records-container {
  flex: 1;
  overflow: hidden;

  .el-scrollbar {
    height: 100%;
  }

  .records-table {
    border: none;
    font-size: 12px;

    .el-table__header th {
      background-color: #fafafa;
      font-weight: 600;
      font-size: 12px;
      padding: 8px 0;
    }

    .el-table__body td {
      padding: 2px 0;
      text-align: center;
    }

    .table-action-btn {
      margin: 0 2px;
    }
    
    /* 垂直排列的操作按钮样式 */
    .action-buttons {
      display: flex;
      flex-direction: column;
      gap: 4px;
      align-items: center;
      justify-content: center;
      width: 100%;
      height: 100%;
    }
    
    .action-buttons .el-button {
      width: 28px;
      height: 24px;
      padding: 0;
      border-radius: 4px;
      margin-left: 0 !important;
      transition: all 0.2s ease;
      display: flex;
      align-items: center;
      justify-content: center;
    }
    
    .action-buttons .el-button:hover {
      transform: scale(1.05);
    }
    
    .action-btn {
      width: 28px;
      height: 24px;
      padding: 0;
      border-radius: 4px;
      display: flex;
      align-items: center;
      justify-content: center;
    }
  }
  
  /* 两行显示的时间范围样式 */
  .time-range {
    display: flex;
    flex-direction: column;
    align-items: center;
    gap: 2px;
  }
  
  .start-time-line,
  .end-time-line {
    font-size: 12px;
    color: #52c41a;
    line-height: 1.4;
    font-weight: 500;
    background-color: rgba(82, 196, 26, 0.1);
    padding: 2px 6px;
    border-radius: 4px;
    border: 1px solid rgba(82, 196, 26, 0.3);
    white-space: nowrap;
  }

  /* 名称单元格样式 - 最多显示2行文本 */
  .name-cell {
    display: -webkit-box;
    -webkit-line-clamp: 2;
    -webkit-box-orient: vertical;
    overflow: hidden;
    text-overflow: ellipsis;
    line-height: 1.3;
    max-height: calc(1.3em * 2);
  }

  .empty-records {
    text-align: center;
    padding: 20px;
    color: #999;
    font-size: 12px;
  }
}

// 播放器区域
.player-section {
  height: 70vh; /* 增加播放器高度以减少空白区域 */
  display: flex;
  flex-direction: column;
  padding: 0; /* 移除边距，使播放器填满整个区域 */
  overflow: hidden;
  background-color: #f0f2f5;
}

.player-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 12px;
  padding: 8px 12px;
  background-color: #fff;
  border-radius: 6px;
  box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);

  .player-info {
    display: flex;
    align-items: center;
    gap: 4px;
    font-size: 14px;
    color: #333;

    .current-time {
      font-weight: 600;
      color: #1890ff;
    }

    .separator {
      color: #999;
    }

    .total-time {
      color: #666;
    }
  }
}

.player-container {
  flex: 1;
  background-color: #000;
  border-radius: 8px;
  position: relative;
  overflow: hidden;
  display: flex;
  align-items: center;
  justify-content: center;

  .main-video-player {
    width: 100%;
    height: 100%;
    object-fit: contain;
  }




}

// 时间轴区域
.timeline-section {
  // height: 150px;
  background-color: #fff;
  border-top: 1px solid #e0e0e0;
  display: flex;
  flex-direction: column;
  overflow: hidden;
  z-index: 5;
}

.timeline-header {
  display: flex;
  align-items: center;
  padding: 6px 12px;
  background-color: #fafafa;
  border-bottom: 1px solid #e8e8e8;

  .timeline-controls {
    display: flex;
    align-items: center;
    gap: 8px;
  }

  .custom-controls {
    display: flex;
    align-items: center;
    gap: 15px;
    margin-left: 20px;

    .control-group {
      display: flex;
      align-items: center;
      gap: 8px;
    }
  }

  .timeline-info {
    font-size: 12px;
    margin-left: auto;

    .selection-info {
      color: #1890ff;
      font-weight: 500;
    }

    .empty-selection {
      color: #999;
    }
  }
}

.timeline-container {
  flex: 1;
  position: relative;
  overflow-x: auto;
  overflow-y: hidden;
  margin-left: 0px;
  margin-right: 10px;
  background-color: #1a1a1a; /* 改为黑色背景 */  
  scrollbar-width: none; /* Firefox */
  -ms-overflow-style: none; /* IE and Edge */
}

.timeline-container::-webkit-scrollbar {
  display: none; /* Chrome, Safari and Opera */
}

// 时间刻度 - 优化后更清晰明显，增加高度以减少空白区域
.time-scale {
  height: 55px;
  position: relative;
  // background-color: #1a1a1a;
  border-bottom: 1px solid #444;
  // 移除overflow: hidden，允许显示所有刻度
  width: 100%;
  min-width: 100%;

  .scale-marks {
    position: absolute;
    top: 0;
    left: 0;
    height: 100%;
    width: 100%;
  }

  .time-mark {
    position: absolute;
    top: 0;
    height: 100%;
    width: 1px;

    .mark-line {
      position: absolute;
      top: 8px;
      bottom: 0;
      width: 1px;
      background-color: rgba(255, 255, 255, 0.4);
    }

    &.major-mark {
      .mark-line {
        background-color: #fff;
        width: 2px;
      }

      .mark-label {
        position: absolute;
        top: 2px;
        left: 2px;
        font-size: 11px;
        color: #fff;
        white-space: nowrap;
        background-color: rgba(0, 0, 0, 0.8);
        padding: 1px 4px;
        border-radius: 2px;
        border: 1px solid rgba(255, 255, 255, 0.2);
      }
    }
  }
}

// 选择区域样式
.selection-range {
  position: absolute;
  top: 0;
  height: 100%;
  background-color: rgba(24, 144, 255, 0.3);
  border: 1px solid #1890ff;
  cursor: move;
  z-index: 15;
}

.selection-handle {
  position: absolute;
  top: 0;
  width: 6px;
  height: 100%;
  background-color: #1890ff;
  cursor: ew-resize;
  border: 1px solid #fff;
  box-sizing: border-box;
}

.left-handle {
  left: 0;
  transform: translateX(-3px);
}

.right-handle {
  right: 0;
  transform: translateX(3px);
}

// 播放头
.playhead {
  position: absolute;
  top: 0;
  height: calc(100% - 5px); // 减去滚动条高度
  width: 2px;
  background-color: #f5222d;
  z-index: 20;

  .playhead-line {
    position: absolute;
    top: 0;
    bottom: 0;
    width: 100%;
    background-color: #f5222d;
  }

  .playhead-knob {
    position: absolute;
    top: -5px;
    left: 50%;
    transform: translateX(-50%);
    width: 12px;
    height: 12px;
    border-radius: 50%;
    background-color: #f5222d;
    border: 2px solid #fff;
    box-shadow: 0 2px 4px rgba(0, 0, 0, 0.3);
  }
}

// 入点出点标记
.point-marker {
  position: absolute;
  top: 0;
  height: calc(100% - 5px); // 减去滚动条高度
  z-index: 15;

  .marker-line {
    position: absolute;
    top: 0;
    bottom: 0;
    width: 2px;
    background-color: currentColor;
  }

  .marker-label {
    position: absolute;
    top: 5px;
    left: 4px;
    font-size: 10px;
    color: currentColor;
    white-space: nowrap;
    background-color: rgba(255, 255, 255, 0.9);
    padding: 1px 4px;
    border-radius: 2px;
    border: 1px solid currentColor;
  }

  &.in-point-marker {
    color: #52c41a;
  }

  &.out-point-marker {
    color: #1890ff;
  }
}





// 时间轴自定义滑块样式 - 简洁优化版
.timeline-scrollbar {
  width: 100%;
  height: 12px; /* 进一步减小高度 */
  background-color: #2a2a2a; /* 调整为更深的灰色，与深色主题更统一 */
  border-radius: 6px; /* 减小圆角 */
  position: relative;
  margin-top: 8px; /* 减小上边距 */
  margin-bottom: 16px; /* 减小下边距 */
  cursor: pointer;
  overflow: visible;
  box-shadow: inset 0 1px 3px rgba(0, 0, 0, 0.5); /* 简化内阴影 */
  border: 1px solid #404040; /* 更细的边框 */
  transition: background-color 0.2s ease;
}

.scrollbar-track {
  width: 100%;
  height: 100%;
  position: relative;
}

.scrollbar-thumb {
  position: absolute !important;
  height: 20px !important; /* 大幅减小滑块高度 */
  width: 30px !important; /* 大幅减小滑块宽度 */
  background-color: #1890ff !important; /* 使用单色背景，简化样式 */
  border-radius: 4px !important; /* 减小圆角 */
  top: 50% !important;
  transform: translateY(-50%) !important;
  cursor: pointer !important;
  box-shadow: 0 2px 6px rgba(0, 0, 0, 0.3) !important; /* 简化阴影 */
  transition: all 0.2s ease !important;
  opacity: 1 !important;
  border: 1px solid rgba(255, 255, 255, 0.2) !important; /* 更细的边框 */
  min-width: 25px !important; /* 减小最小宽度 */
  max-width: 100px !important; /* 减小最大宽度 */
  display: flex !important;
  align-items: center !important;
  justify-content: center !important;
  z-index: 20 !important;
  user-select: none;
  -webkit-user-select: none;
  touch-action: none;
}

.thumb-indicator {
  width: 6px;
  height: 2px;
  background-color: rgba(255, 255, 255, 0.8);
  position: absolute;
  border-radius: 1px;
}

.thumb-indicator.left {
  left: 8px;
}

.thumb-indicator.right {
  right: 8px;
}

.scrollbar-thumb:hover {
  background-color: #40a9ff !important;
  transform: translateY(-50%) !important;
  box-shadow: 0 3px 8px rgba(0, 0, 0, 0.4) !important;
}

.scrollbar-thumb:active {
  background-color: #096dd9 !important;
  transform: translateY(-50%) !important;
  box-shadow: 0 4px 10px rgba(0, 0, 0, 0.5) !important;
}

.timeline-scrollbar:hover {
  background-color: #333333 !important;
  border-color: #555 !important;
}

// 时间轴容器样式调整，保持简洁
.timeline-container {
  transition: margin-right 0.3s ease;
}

// 响应式适配 - 移动端优化
@media (max-width: 768px) {
  .timeline-scrollbar {
    height: 24px; /* 移动端略微增加高度 */
    border-radius: 12px;
  }
  
  .scrollbar-thumb {
    width: 50px !important; /* 移动端略微增加宽度 */
    height: 34px !important; /* 移动端略微增加高度 */
    min-width: 40px !important;
    background-color: #3B82F6 !important;
    border-radius: 8px !important;
    box-shadow: 0 3px 6px rgba(0, 0, 0, 0.25) !important;
  }
}




// 入点出点截图区域样式
.image-container {
  width: 100%;
  height: 100px;
  background-color: #00060a;
  border: 1px solid #00060a;
  border-radius: 6px;
  padding: 8px;
  margin-top: 8px;
  box-sizing: border-box;
  overflow-x: auto;
  overflow-y: hidden;
  display: flex;
  gap: 16px;
  white-space: nowrap;
  -webkit-overflow-scrolling: touch;
  scrollbar-width: thin;
  scrollbar-color: #91d5ff #e6f7ff;
}

.screenshot-wrapper {
  display: flex;
  height: 100%;
  gap: 12px;
  overflow-x: auto;
}

.screenshot-list {
  display: flex;
  gap: 8px;
  margin-bottom: 8px;
  overflow-x: auto;
  padding-bottom: 4px;
  white-space: nowrap;
}

.screenshot-item {
  flex: 0 0 auto;
  width: 150px;
  height: 100%;
  position: relative;
  border-radius: 4px;
  overflow: hidden;
}

.screenshot-with-overlay {
  width: 100%;
  height: 100%;
  position: relative;
}

.screenshot-image {
  width: 100%;
  height: 100%;
  object-fit: cover;
}

.screenshot-overlay {
  position: absolute;
  bottom: 0;
  left: 0;
  right: 0;
  background: rgba(0, 0, 0, 0.7);
  color: white;
  padding: 4px 6px;
  display: flex;
  align-items: center;
  justify-content: space-between;
}

.overlay-content {
  flex: 1;
}

.screenshot-type {
  font-size: 12px;
  font-weight: bold;
  margin-bottom: 2px;
}

.screenshot-time {
  font-size: 11px;
  font-family: monospace;
  opacity: 0.9;
}

.delete-btn {
  width: 20px;
  height: 20px;
  border: none;
  background-color: rgba(255, 255, 255, 0.2);
  color: white;
  border-radius: 3px;
  cursor: pointer;
  display: flex;
  align-items: center;
  justify-content: center;
  transition: background-color 0.2s;
}

.delete-btn:hover {
  background-color: rgba(255, 255, 255, 0.3);
}

.screenshot-placeholder {
    width: 100%;
    height: 100%;
    min-height: 60px;
    background-color: #1a1a1a;
    display: flex;
    justify-content: center;
    align-items: center;
    color: #ccc;
    font-size: 12px;
    text-align: center;
    padding: 10px 8px;
    border-radius: 4px;
    border: 1px solid #333;
  }

.loading-spinner {
  font-size: 16px;
  margin-bottom: 4px;
  animation: spin 1s linear infinite;
}

@keyframes spin {
  0% { transform: rotate(0deg); }
  100% { transform: rotate(360deg); }
}

// 响应式设计
@media (max-width: 1200px) {
  .info-panel {
    width: 250px;
  }
  
  .timeline-section {
    left: 250px;
  }
}

@media (max-width: 992px) {
  .editor-container {
    flex-direction: column;
  }

  .info-panel {
    width: 100%;
    height: auto;
    max-height: 300px;
  }

  .player-container {
    height: 400px;
  }
}

@media (max-width: 768px) {
  .top-toolbar {
    padding: 8px 12px;

    .page-title {
      font-size: 16px;
    }

    .action-btn {
      padding: 6px 12px;
    }
  }

  .player-section {
    padding: 12px;
  }

  .player-container {
    height: 300px;
  }

  .timeline-section {
    height: 250px;
  }
  
  .image-container {
    display: block;
    gap: 0;
    overflow-x: hidden;
    overflow-y: auto;
    height: auto;
    max-height: 200px;
    white-space: normal;
    -webkit-overflow-scrolling: touch;
    scrollbar-width: thin;
    scrollbar-color: #91d5ff #e6f7ff;
  }
  
  .screenshot-wrapper {
    flex-direction: column;
    gap: 16px;
  }
  
  .screenshot-item {
    min-width: auto;
  }
  
  .screenshot-divider {
    transform: rotate(90deg);
    margin-top: 0;
    align-self: center;
  }
  
  .screenshot-list {
    gap: 6px;
    overflow-x: auto;
    white-space: nowrap;
  }
}
</style>




